import axios, { type AxiosInstance, type AxiosResponse, type AxiosRequestConfig, type AxiosRequestHeaders } from 'axios'
import { showFailToast } from 'vant'
import { getToken } from '@/utils'
import { type Result } from '@/utils/types'
import { NProgress } from '@/plugins/nprogress'
import { toEncryption } from './encryption'
NProgress.configure({ showSpinner: false })
// 基础配置
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
  headers: {
    token: getToken(),
  },
})
// 接口提示信息
function showInfo(res: Partial<Result>): void {
  const info = res.msg || res.message || '请求失败'
  showFailToast(info)
}
// 请求拦截
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    NProgress.start()
    const requestHeaders = config.headers as AxiosRequestHeaders
    // requestHeaders.timestamp = String(Math.floor(new Date().valueOf() / 1000))
    requestHeaders.sign = toEncryption(config.data || config.params || {})
    return config
  },
  (error) => {
    NProgress.done()
    console.error('请求错误：', error)
  }
)
// 相应拦截
service.interceptors.response.use(
  async (response: AxiosResponse): Promise<Result> => {
    NProgress.done()
    const res = response.data
    if (`${res.code as string | number}` !== '200') {
      showInfo(res)
      return await Promise.reject(res)
    }
    return await Promise.resolve(res)
  },
  async (error) => {
    NProgress.done()
    showInfo(error)
    return await Promise.reject(error)
  }
)
export default async function request(config: AxiosRequestConfig): Promise<Result> {
  return await service({ method: 'get', ...config }).then((res: AxiosResponse<Result>) => ({ ...res }))
}
